package com.luoxc.filter;

import com.alibaba.fastjson.JSONObject;
import com.luoxc.pojo.Result;
import com.luoxc.utils.JwtHandle;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@Slf4j
//@WebFilter(urlPatterns = "/*")
public class LoginFilter implements Filter {

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;

        // 1. 检查请求路径是否是login 登录
            // 获取路径
            String url = request.getRequestURI();
            log.info("请求路径为:" + url);
            if(url.equals("/login")){
                log.info("当前为登录,放行");
                filterChain.doFilter(servletRequest,servletResponse);
                return;
            }
        // 2. 判断是否携带token
        String token = request.getHeader("token");
            log.info("token值为:"+token);
        if(!StringUtils.hasLength(token)){
            log.info("没有token");
            Result error = Result.error("not_login");
            // 手动转为json
            String jsonString = JSONObject.toJSONString(error);
            response.getWriter().write(jsonString);
            return;
        }
        // 3. 判断携带的token 是否正确
        try {
            JwtHandle.parseJwt(token);
        } catch (Exception e) {
            log.info("捕获错误");
            e.printStackTrace();
            Result error = Result.error("not_login");
            String jsonString = JSONObject.toJSONString(error);
            response.getWriter().write(jsonString);
            return;
        }
        // 4. 放行
        filterChain.doFilter(servletRequest,servletResponse);

    }
}
